//
//  SignalVisualizer.m
//  AffichageSignal
//
//  Created by Pierre DUCHENE on 09/02/10.
//  Copyright 2010 Pierre DUCHENE. All rights reserved.
//

#import "SignalVisualizer.h"
#import "Signal.h"
#import "SignalView.h"
#import "AudioWrapper.h"
#import "System.h"

@implementation SignalVisualizer
@synthesize model;
@synthesize started;

#pragma mark -
#pragma mark Singleton implementation
static SignalVisualizer* sharedVisualizer = nil;

+ (SignalVisualizer*)sharedSignalVisualizer
{
    if (sharedVisualizer == nil) {
        sharedVisualizer = [[super allocWithZone:NULL] init];
    }
    return sharedVisualizer;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [[self sharedSignalVisualizer] retain];
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}

- (void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}




- (id) init
{
	self = [super init];
	if (self != nil) {
		started = NO;
		model = [[Signal alloc] init];
		SignalView* s = [[SignalView alloc] initWithFrame:NSMakeRect(0, 0, 636, 171)];
		[s setController:self];
		[self setView:s];
		[s release];
		s = nil;
		
		/*debugWindow = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 500, 1500, 200)
												  styleMask:NSTexturedBackgroundWindowMask
													backing:NSBackingStoreBuffered
													  defer:YES];
		[debugWindow setIsVisible:YES];
		[debugWindow setContentView:self.view];
		*/
	}
	return self;
}


- (void)addSample:(NSArray*)aSample
{
	[model addSample:aSample];
	[self.view setNeedsDisplay:YES];
}

- (void)setSignal:(NSArray*)aSignal
{
	[model setValues:aSignal];
	[self.view setNeedsDisplay:YES];
}

- (void)displayOutputSignal
{
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
	
	while (started) {
		NSAutoreleasePool* poolTmp = [[NSAutoreleasePool alloc] init];
		/*NSArray* audioSignal = [[AudioWrapper sharedWrapper] buffer];
		[model addSample:audioSignal];*/
		[model updateAudioSignal];
		[self.view setNeedsDisplay:YES];
		[NSThread sleepForTimeInterval:[[System sharedSystem] sampleDuration]];
		[poolTmp drain];
	}
	
	[pool drain];
}

@end
